/*
 * Copyright 2014-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wzq.framework.mvc;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @author <a href="mailto:yanghao@01mi.net">杨浩</a>
 */
@RestController
@RequestMapping("/api")
public class DefaultApiController extends AbstractApiController {
	protected final Logger logger = LogManager.getLogger(getClass());
	@Autowired
	private ApplicationContext appContext;
	private Map<String, ApiHandlerMethod> methodMap = new HashMap<>();
	
	@PreDestroy
	public void destroy() {
		appContext = null;
		methodMap = new HashMap<>();
	}
	
	public void setMethods(String[] methods) throws Exception {
		for (String method : methods) {
			int pos = method.lastIndexOf(".");
			String className = method.substring(0, pos), methodName = method.substring(pos + 1);
			
			Class<?> clazz = Class.forName(className);
			Object bean = appContext.getBean(clazz);
			for (Method tmp : clazz.getMethods()) {
				if (tmp.getName().equals(methodName)) {
					ApiHandlerMethod old = methodMap.put(method, new ApiHandlerMethod(bean, tmp));
					if (old != null) throw new IllegalArgumentException("存在重复method：" + method);
				}
			}
		}
	}

	/** 自动路由模式 */
	@RequestMapping
	public Object autoApi(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method = request.getParameter("method");
		ApiHandlerMethod handlerMethod = methodMap.get(method);
		if (handlerMethod == null) throw new IllegalArgumentException("api=" + method + " 不存在");
		return handlerMethod.invokeForRequest(new ServletWebRequest(request, response));
	}

}

